/**
 * 
 */
package jmath.function.impl;

import java.util.*;
import jmath.function.*;

/**
 * @author timon
 * 
 */
public class ThreadedFunction implements Startable{
	
	private List<Startable> modelList;

	private int workingThreadCount = 0;
	
	private final int maximumThreadCount = 2;

	public ThreadedFunction() {
		modelList=new ArrayList<Startable>();
	}	

	public void addToStartableList(Startable startable) {
		modelList.add(startable);
	}

	public void start() {
		for (Startable startable : modelList) {			
			if(getWorkingThreadCount()<maximumThreadCount){
				final Startable localStartable=startable;
				new Thread() {
					public void run() {
						increaseWorkingThreadCount();
						localStartable.start();
						decreaseWorkingThreadCount();
					}
				}.start();
			}
			
			try {
				Thread.currentThread().wait(1000);
			} catch (Exception ignored) {
			}
			
		}
		while(getWorkingThreadCount()>0){
			try {
				Thread.currentThread().wait(2000);
			} catch (Exception ignored) {
			}
		}
	}
	
	private synchronized int getWorkingThreadCount(){
		return workingThreadCount;
	}
	private synchronized void increaseWorkingThreadCount(){
		workingThreadCount=workingThreadCount+1;
	}
	private synchronized void decreaseWorkingThreadCount(){
		workingThreadCount=workingThreadCount-1;
	}
	
	
}
